/* Copyright (C) 2010-2011, Mamadou Diop.
*  Copyright (C) 2011, Doubango Telecom.
*
* Contact: Mamadou Diop <diopmamadou(at)doubango(dot)org>
*	
* This file is part of imsdroid Project (http://code.google.com/p/imsdroid)
*
* imsdroid is free software: you can redistribute it and/or modify it under the terms of 
* the GNU General Public License as published by the Free Software Foundation, either version 3 
* of the License, or (at your option) any later version.
*	
* imsdroid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
* See the GNU General Public License for more details.
*	
* You should have received a copy of the GNU General Public License along 
* with this program; if not, write to the Free Software Foundation, Inc., 
* 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package org.doubango.FrCall.Screens;

import org.doubango.FrCall.CustomDialog;
import org.doubango.FrCall.FrCall;
import org.doubango.FrCall.Main;
import org.doubango.FrCall.OpenfireNetService;
import org.doubango.FrCall.OpenfireRosterService;
import org.doubango.FrCall.R;
import org.doubango.FrCall.Utils.RosterStoreManager;
import org.doubango.FrCall.Utils.SystemMessageManager;
import org.doubango.FrCall.Utils.UserStoreManager;
import org.doubango.FrCall.model.User;
import org.doubango.FrCall.model.UserStore;
import org.doubango.ngn.events.NgnEventArgs;
import org.doubango.ngn.events.NgnRegistrationEventArgs;
import org.doubango.ngn.services.INgnConfigurationService;
import org.doubango.ngn.services.INgnSipService;
import org.doubango.ngn.utils.NgnConfigurationEntry;

import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * @author lihu
 * 登陆界面
 */
public class ScreenLogin extends BaseScreen {
	private static final String TAG = ScreenLogin.class.getCanonicalName();

	private static final int REQ_SYSTEM_SETTINGS = 0;
	private static INgnSipService mSipService;
	private static INgnConfigurationService mConfigurationService;
	private BroadcastReceiver mSipBroadCastRecv;
	
	public ScreenLogin() {
		super(SCREEN_TYPE.LOGIN, TAG);
		mSipService = getEngine().getSipService();
		mConfigurationService = getEngine().getConfigurationService();
	}
	private SharedPreferences sp;
	 Editor editor;
	 
	EditText id, pw;
	CheckBox check;
	ImageButton registBtn ,loginBtn ;
	ImageButton setBtn;
	String username,password;
	RelativeLayout frameSets;
	LinearLayout frame1 //登录界面
				,frame2;//登录中界面
	private boolean JudgeLogin = !false;
	Builder setIP_Dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_login);
		if(sysDB == null)
			sysDB = new SystemMessageManager(this);
		if(userDB == null)
			userDB = new UserStoreManager(this);
		if(rosterDB == null)
			rosterDB = new RosterStoreManager(this);
        //读取本地存储的用户登录信息
        sp = getSharedPreferences("user_msg", 0);
		editor= sp.edit();
        username = sp.getString("username", "");
		password = sp.getString("password", "");
		JudgeLogin = sp.getBoolean("Can_save", false);
		//对各种控件进行初始化
		check = (CheckBox) findViewById(R.id.Screen_Login_CheckSave_CKB);
		check.setChecked(JudgeLogin);
		check.setOnClickListener(clicker);
		loginBtn = (ImageButton) findViewById(R.id.Screen_Login_login_But);
		registBtn = (ImageButton) findViewById(R.id.Screen_Login_regist_But);
		setBtn = (ImageButton) findViewById(R.id.Screen_Login_Setting_But);
		id = (EditText) findViewById(R.id.Screen_Login_UserID_Edt);
		id.setText(username);
		pw = (EditText) findViewById(R.id.Screen_Login_UserPWD_Edt);
		pw.setText(password);
		loginBtn.setOnClickListener(clicker);
		registBtn.setOnClickListener(clicker);
		setBtn.setOnClickListener(clicker);
		frameSets=(RelativeLayout) findViewById(R.id.Screen_Login_Frame_Sets);
		frame1=(LinearLayout) findViewById(R.id.Screen_Login_Frame_1);
		frame1.setVisibility(View.VISIBLE);
		frame2=(LinearLayout) findViewById(R.id.Login_Frame_2);
		frame2.setVisibility(View.INVISIBLE);
		//设置登录监听服务
		pDialog = new ProgressDialog(this);
		mSipBroadCastRecv = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if(action.equals(getResources().getString(R.string.OPENFIRE_ACTION_RES_LOGIN)))
				{
					boolean isSuccess = intent.getBooleanExtra(getResources().getString(R.string.RES_LOGIN_RESULT),false);
					if(isSuccess)
					{
						FrCall.user = new User();
						FrCall.user.setUserId(mOpenfireService.getLoginUser());
	 					ListHander.sendEmptyMessage(LOAD_CARD);
	 					toastText = "登录成功";
	 					toastTime = Toast.LENGTH_SHORT;
	 					ListHander.sendEmptyMessage(SHOW_TOAST_TEXT);
					}
					else
					{
	 					toastText = "登录失败";
	 					toastTime = Toast.LENGTH_SHORT;
	 					beCancelPDialog=true;
	 					ListHander.sendEmptyMessage(SHOW_TOAST_TEXT);
					}
					return;
				}
				if(action.equals(getResources().getString(R.string.OPENFIRE_ACTION_RES_LOAD_CARD)))
				{
					boolean isSuccess = intent.getBooleanExtra(getResources().getString(R.string.RES_CARD_RESULT), false);
					if(isSuccess)
					{
						FrCall.user.setvCard(OpenfireNetService.getTempCard());
						if(mSipService.register(ScreenLogin.this))//提交登录请求。同时切换到登录中界面
						{
							frame2.setVisibility(View.VISIBLE);
							frame1.setVisibility(View.INVISIBLE);
						}
//						ListHander.sendEmptyMessage(LOGIN_TO_MM);
					}
					else
					{
						toastText = "获取用户信息失败";
	 					toastTime = Toast.LENGTH_SHORT;
	 					beCancelPDialog=true;
	 					ListHander.sendEmptyMessage(SHOW_TOAST_TEXT);
					}
					return;
				}
				if(action.equals(getResources().getString(R.string.OPENFIRE_ACTION_RES_CONNECT)))
				{
					boolean connectOK=intent.getBooleanExtra(getResources().getString(R.string.RES_LOGIN_RESULT),false);
					if(connectOK)
					{
						login();
					}
					else
					{
						beCancelPDialog=true;
						toastText = "连接服务器失败";
	 					toastTime = Toast.LENGTH_SHORT;
	 					beCancelPDialog=true;
	 					ListHander.sendEmptyMessage(SHOW_TOAST_TEXT);
					}
					return;
				}
				// Registration Event
				if(NgnRegistrationEventArgs.ACTION_REGISTRATION_EVENT.equals(action)){
					NgnRegistrationEventArgs args = intent.getParcelableExtra(NgnEventArgs.EXTRA_EMBEDDED);
					if(args == null){
						Log.e(TAG, "Invalid event args");
						return;
					}
					switch(args.getEventType()){
						case REGISTRATION_NOK:
						case UNREGISTRATION_OK:
							pDialog.dismiss();
							frame1.setVisibility(View.VISIBLE);
							frame2.setVisibility(View.INVISIBLE);
							break;
						case REGISTRATION_OK:
							ListHander.sendEmptyMessage(LOGIN_TO_MM);
//							pDialog.dismiss();
//							ScreenLogin.this.finish();
//							login();
//							if(mScreenService.show(ScreenHome.class))
//								getEngine().getConfigurationService().putBoolean(NgnConfigurationEntry.GENERAL_AUTOSTART, true);
							break;
						case REGISTRATION_INPROGRESS:
							break;
						case UNREGISTRATION_INPROGRESS:
						case UNREGISTRATION_NOK:
							pDialog.dismiss();
							frame1.setVisibility(View.VISIBLE);
							frame2.setVisibility(View.INVISIBLE);
							break;
						default:
							break;
					}
				}
			}
		};
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(NgnRegistrationEventArgs.ACTION_REGISTRATION_EVENT);
		intentFilter.addAction(getResources().getString(R.string.OPENFIRE_ACTION_RES_LOGIN));
		intentFilter.addAction(getResources().getString(R.string.OPENFIRE_ACTION_RES_CONNECT));
		intentFilter.addAction(getResources().getString(R.string.OPENFIRE_ACTION_RES_LOAD_CARD));
		if(!mSipService.isRegistered())
		{
			registerReceiver(mSipBroadCastRecv, intentFilter);
		}
	}
	@Override
	protected void onDestroy() {
       if(mSipBroadCastRecv != null){
    	   unregisterReceiver(mSipBroadCastRecv);
    	   mSipBroadCastRecv = null;
       }
        
       super.onDestroy();
	}
	@Override
	public boolean hasBack() {
		// TODO Auto-generated method stub
		return true;
	}
	@Override
	public boolean back() {
		if(pDialog.isShowing())
		{
			pDialog.dismiss();
			mOpenfireService.getXMPPConnection().disconnect();
		}
		else {
			CustomDialog.show(this, R.drawable.exit_48, "退出", "是否退出", "确定", new OnClickListener() {
				@Override
				public void onClick(View v) {
					CustomDialog.dialog.dismiss();
					((Main)(getEngine().getMainActivity())).exit();
					getEngine().stop();
					stopService(((Main)(getEngine().getMainActivity())).getIntent());
					finish();
				}
			}, "取消", new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					CustomDialog.dialog.dismiss();
				}
			});
		}
		return false;
	}
	public void onBackPressed() {};
	View.OnClickListener clicker = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.Screen_Login_login_But: {
				if (validate()) {
					//获取ip，设置网络连接环境
					String hostIP = mConfigurationService.getString(NgnConfigurationEntry.NETWORK_PCSCF_HOST, NgnConfigurationEntry.DEFAULT_NETWORK_PCSCF_HOST).trim();
					mConfigurationService.putString(NgnConfigurationEntry.IDENTITY_DISPLAY_NAME, 
							username.toString().trim());
					mConfigurationService.putString(NgnConfigurationEntry.IDENTITY_IMPU, 
							("sip:"+username.trim()+"@"+hostIP).trim());
					mConfigurationService.putString(NgnConfigurationEntry.IDENTITY_IMPI, 
							(username.trim()).trim());
					mConfigurationService.putString(NgnConfigurationEntry.IDENTITY_PASSWORD, 
							password.trim());
					mConfigurationService.putString(NgnConfigurationEntry.NETWORK_REALM, 
							("sip:"+hostIP).trim());
					//存储到本地
					if(!mConfigurationService.commit()){
						Log.e(TAG, "Failed to commit() configuration");
					}
					//判断是否要存储用户名密码
					if(JudgeLogin)
					{
						editor.putString("username", username);
						editor.putString("password", password);
						editor.commit();
					}

					FrCall.s_MyUserID = username;
					mOpenfireService.setConfig(hostIP);
					if(!OpenfireNetService.mConnection.isConnected())
					{
						startService(new Intent(ScreenLogin.this,mOpenfireService.getClass()));
						pDialog.setTitle("请稍后");
						pDialog.setMessage("正在连接服务器...");
						pDialog.setCancelable(!true);
						if(!pDialog.isShowing())
							pDialog.show();
					}
					else
					{
						login();
					}
					BaseScreen.mInputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
//					Intent intent = new Intent(this, LoginingActivity.class);
//					startActivityForResult(intent,0);
				}
			}
				break;
			case R.id.Screen_Login_Setting_But:
				//进入到设置界面
				Intent intent1 = new Intent(ScreenLogin.this,
						ScreenSimpleSetting.class);
				startActivityForResult(intent1,REQ_SYSTEM_SETTINGS);
				break;
			case R.id.Screen_Login_CheckSave_CKB:
				CheckBox c = (CheckBox) v;
				JudgeLogin = c.isChecked();
				editor.putBoolean("Can_save", JudgeLogin);
				editor.putString("username", username);
				editor.putString("password", password);
				editor.commit();
				break;
			case R.id.Screen_Login_regist_But:
				Intent intent2 = new Intent(ScreenLogin.this,
						RegisterSelect.class);
				startActivityForResult(intent2,REQ_SYSTEM_SETTINGS);
				break;
			default:
				break;
			}
		}
	};
	public class DBTask extends AsyncTask<Object,Object,Object>{

		@Override
		protected Object doInBackground(Object... params) {
			UserStore user = new UserStore(username, check.isChecked()?password:""); 
			userDB.insert(user);
			userDB.close();
			return null;
		}
		
	}
	public static String toastText = "";
	public static int toastTime = Toast.LENGTH_SHORT;
	public final static int LOGIN_TO_MM = 0;
	public final static int SHOW_TOAST_TEXT = 2;
	public final static int LOAD_CARD = 1;
	public static boolean beCancelPDialog=false;
	public Handler ListHander = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOGIN_TO_MM:
//				if(mSipService.register(ScreenLogin.this))//提交登录请求。同时切换到登录中界面
//				{
//					frame2.setVisibility(View.VISIBLE);
//					frame1.setVisibility(View.INVISIBLE);
//				}
				FrCall.s_MyUserID = username;
				mScreenService.destroy(getId());
				new DBTask().execute("");
				pDialog.dismiss();
				FrCall.user.getvCard().setField(User.VCARD_FIELD_ONLINE_STATUS, "在线");
				FrCall.user.save();
//		        startService(new Intent(getBaseContext(), OpenfireRosterService.class));
				mScreenService.show(ScreenHome.class);
				getEngine().getConfigurationService().putBoolean(NgnConfigurationEntry.GENERAL_AUTOSTART, true);
				mScreenService.destroy(getId());
//				loginThread.destroy();
//				if(loginThread!=null && loginThread.isAlive())		
//					loginThread.stop();
//				loginThread=null;
				break;
			case LOAD_CARD:
				Intent intent = new Intent(getResources().getString(R.string.OPENFIRE_ACTION_REQ_LOAD_CARD));
				intent.putExtra(getResources().getString(R.string.REQ_CARD_USER),FrCall.user.toString());
				sendBroadcast(intent);
				break;
			case SHOW_TOAST_TEXT:
				if(beCancelPDialog)
					pDialog.dismiss();
				Toast.makeText(getApplicationContext(),toastText, toastTime).show();
				break;
			default:
				// do something11. break;
			}
		}
	};
	protected ProgressDialog pDialog;
	 public void login(){
		 if(pDialog==null)
			 pDialog = new ProgressDialog(this);
			pDialog.setTitle("请稍后");
			pDialog.setMessage("正在登录...");
			pDialog.setCancelable(true);
			pDialog.show();
			Intent intent = new Intent(getResources().getString(R.string.OPENFIRE_ACTION_REQ_LOGIN));
			intent.putExtra(getResources().getString(R.string.REQ_LOGIN_USERNAME), username);
			intent.putExtra(getResources().getString(R.string.REQ_LOGIN_PASSWORD), password);
			intent.putExtra(getResources().getString(R.string.REQ_LOGIN_STATUS), String.valueOf(false/*status_hide.isChecked()*/));
			sendBroadcast(intent);
	    }
	/**
	 * @return 验证用户名是否符合而要求
	 */
	private boolean validate(){
		 username = id.getText().toString();
		if(username.equals("")){
			Toast.makeText(this, "用户名不能为空！", Toast.LENGTH_SHORT).show();
			return false;
		}
		if(username.indexOf("@")>=0)
		{
			Toast.makeText(this, "用户名不能含有特殊字符！", Toast.LENGTH_SHORT).show();
			return false;
		}
		 password = pw.getText().toString();
		if(password.equals("")){
			Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

}
